import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import pyqtSlot
from ping import Ui_MainWindow
import threading
import subprocess
import time
from queue import Queue
import tempfile

# 定义sucess列表、工作进程数和初始化队列
ipSuccess = []
# ipFaild = []
Work_Thread = 254
ipQueue = Queue()

# 初始化主窗口类


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.statusbar.showMessage("在线台数:0")

    # 响应按钮点击动作
    @pyqtSlot()
    def on_ping_clicked(self):
        start_time = time.time()
        # 清除旧颜色
        for i in range(1, 255):
            ui_default = 'ui.ip_' + \
                str(i) + '.setStyleSheet("background-color: rgb(217, 217, 217)")'
            eval(ui_default)

        # 清除状态栏
        ui.statusbar.showMessage("在线台数:0")

        # background-color: rgb(217, 217, 217)
        # 获取网段信息并加入队列
        a = self.ip_line.text()
        if len(a) > 0 and len(a.split('.')) == 4 and a.split('.')[-1] == '':
            for i in range(1, 255):
                ipQueue.put(a + str(i))

            # 开启多线程消费队列
            threads = []
            for i in range(Work_Thread):
                thread = threading.Thread(target=pingIp)
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()

            # 可以ping通的存入sucess列表
            for i in ipSuccess:
                ip_green = 'ip_' + str(i.split(a)[1])
                ui_info = 'ui.' + ip_green + \
                    '.setStyleSheet("background-color:green")'  # 修改UI标签背景为绿色
                eval(ui_info)

            time_info = format(time.time() - start_time, '.2f')
            statusbar_info = '在线台数:' + \
                str(len(ipSuccess)) + ' '*5+'执行耗时:' + time_info + 's'

            # 显示状态栏信息
            ui.statusbar.showMessage(statusbar_info)
            # 清除列表，避免重复统计
            ipSuccess.clear()
            QMessageBox.information(self, "温馨提示", "操作执行完毕！")

        else:
            # 消息框提醒
            QMessageBox.information(self, "温馨提示", "请输入正确的IP网段信息!")


# 执行的ping逻辑


def pingIp():
    # 消费队列里的IP地址
    while not ipQueue.empty():
        ip = ipQueue.get()
        cmd = 'ping -n 2 -w 5 %s' % ip
        # res = subprocess.call(cmd, stdout=subprocess.PIPE)

        # startupinfo = subprocess.STARTUPINFO()
        # startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
        # startupinfo.wShowWindow = subprocess.SW_HIDE
        # res = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        #                        startupinfo=startupinfo).wait()

        # 处理Pyinstaller 打包时subprocess卡死的问题
        # si = subprocess.STARTUPINFO()
        # si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        # res = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,
        #                        stderr=subprocess.STDOUT, universal_newlines=True, startupinfo=si)
        out_temp = tempfile.TemporaryFile(mode='w+')
        fileno = out_temp.fileno()
        p = subprocess.call(cmd, stdout=fileno, stderr=fileno)

        # si = subprocess.STARTUPINFO()
        # si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        # res = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL,
        #                        stderr=subprocess.STDOUT, universal_newlines=True, startupinfo=si)
        # 官方建议的方式
        # res.communicate()

        # print(ip, True if res == 0 else False)

        # 判断返回值是0（0代表命令成功执行）
        # if res.returncode == 0:
        if p == 0:

            # 成功返回0，将从队列中遍历的IP信息存入成功列表
            ipSuccess.append(ip)


if __name__ == '__main__':
    # 初始化PyQt5窗口
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())
